﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.IO.Compression;
using System.Linq;
using System.Reflection.Emit;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace BMWKT
{
	public partial class GameSaved : Form
	{
		private string filePath = string.Empty;

		private bool isLookBackupFile = false;

		private string backupZipPath = string.Empty;

		private string decompressionPath = string.Empty;

		public GameSaved()
		{
			InitializeComponent();
			ProgramInitialization();
		}

		private void ProgramInitialization() 
		{
			new GetBMWKInstallPathForProcess();
			if (GetBMWKInstallPathForProcess.IsGetInstallPath)
			{
				label1.Text = "获取成功！";
				button2.Enabled = true;
				comboBox1.Enabled = true;
				checkBox1.Enabled = true;
				textBox1.Enabled = true;
				new GameSavedPathManage();
				GameSavedPathManage.PopulateComboBoxWithOptions(comboBox1);
			}
			else 
			{
				label1.Text = "获取失败，游戏未启动！";
				isLookBackupFile = true;
			}
		}

		private void CheckedListBox1_ItemCheck(object sender, ItemCheckEventArgs e)
		{
			// 如果选择的是"Checked"状态，那么取消其他项的选中
			if (e.NewValue == CheckState.Checked)
			{
				for (int i = 0; i < checkedListBox1.Items.Count; i++)
				{
					// 如果选中状态是"Unchecked"并且不是当前正在检查的项，则取消选中
					if (i != e.Index)
					{
						checkedListBox1.SetItemChecked(i, false);
					}
				}
			}

			if (isLookBackupFile)
			{
				button3.Enabled = true;
				string fileName = checkedListBox1.Text;
				backupZipPath = ReadGameSavedBackupInfo.GetGameSavedBackupFilePath(fileName);
				decompressionPath = ReadGameSavedBackupInfo.GetGameSavedOriginalFilePath(fileName);
				textBox1.Text = decompressionPath;
				string message = $"游戏存档备份: {fileName}\n\n存档大小: {ReadGameSavedBackupInfo.GetGameSavedBackupFileSize(fileName)}\n\n备份时间: {ReadGameSavedBackupInfo.GetGameSavedBackupFileTime(fileName)}\n\n备份路径: {backupZipPath}";
				label1.Text = message;
			}
			else
			{
				string subDirPath = Path.Combine(filePath, checkedListBox1.Text);
				DisplayDirectoryInfo(subDirPath);
				button2.Enabled = true;
				checkBox1.Enabled = true;
				textBox1.Enabled = true;
				textBox1.Visible = true;
			}
		}

		private void DisplayDirectoryInfo(string subDirPath)
		{
			if (Directory.Exists(subDirPath))
			{
				DirectoryInfo dirInfo = new DirectoryInfo(subDirPath);

				// 获取最后一个目录的信息
				string dirName = dirInfo.Name;
				long dirSize = GetDirectorySize(dirInfo);
				string dirModifiedTime = dirInfo.LastWriteTime.ToString("yyyy年MM月dd日HH时mm分ss秒");

				// 格式化大小字符串
				string dirSizeString = GetFileSizeString(dirSize);

				// 构建显示信息
				string message = $"游戏存档: {dirName}\n\n存档大小: {dirSizeString}\n\n保存时间: {dirModifiedTime}";

				// 显示到标签中
				label1.Text = message;
			}
			else
			{
				label1.Text = "存档目录不存在";
			}
		}

		private long GetDirectorySize(DirectoryInfo directoryInfo)
		{
			long size = 0;

			// 获取目录中所有文件的大小
			FileInfo[] files = directoryInfo.GetFiles();
			foreach (FileInfo file in files)
			{
				size += file.Length;
			}

			// 递归获取子目录的大小
			DirectoryInfo[] subDirs = directoryInfo.GetDirectories();
			foreach (DirectoryInfo subDir in subDirs)
			{
				size += GetDirectorySize(subDir);
			}

			return size;
		}

		private string GetFileSizeString(long size)
		{
			string[] sizeSuffixes = { "字节", "KB", "MB", "GB", "TB" };
			double readableSize = size;
			int order = 0;

			while (readableSize >= 1024 && order < sizeSuffixes.Length - 1)
			{
				order++;
				readableSize /= 1024;
			}

			return $"{readableSize:F2} {sizeSuffixes[order]}";
		}

		private void button1_Click(object sender, EventArgs e)
		{
			new ReadGameSavedBackupInfo();
			textBox1.Enabled = true;
			textBox1.Visible = true;
			button2.Enabled = false;
			List<string> backupFileNames = ReadGameSavedBackupInfo.GetGameSavedBackupFileName("玩家存档");

			checkedListBox1.Items.Clear();

			foreach (var fileName in backupFileNames)
			{
				checkedListBox1.Items.Add(fileName);
			}
			isLookBackupFile = true;
		}

		private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
		{
			isLookBackupFile = false;
			textBox1.Enabled = false;
			textBox1.Visible = false;
			button3.Enabled = false;
			checkBox1.Enabled = false;
			button2.Enabled = true;
			if (!string.IsNullOrEmpty(comboBox1.Text))
			{
				filePath = Path.Combine(GetBMWKInstallPathForProcess.GameSavedPath, GameSavedPathManage.GetFilePathByOptionName(comboBox1.Text));
				// 判断 filePath 是否存在
				if (Directory.Exists(filePath))
				{
					// 获取 filePath 路径中的最后一个目录
					string lastDirectory = Path.GetFileName(filePath);

					// 获取最后一个目录下的所有子目录
					string[] subDirectories = Directory.GetDirectories(filePath);

					// 清空 checkedListBox1 以防之前的内容
					checkedListBox1.Items.Clear();
					label1.Text = "";
					// 将子目录添加到 checkedListBox1 中
					foreach (string subDir in subDirectories)
					{
						// 使用最后一个目录的子目录名作为选项
						string subDirName = Path.GetFileName(subDir);
						checkedListBox1.Items.Add(subDirName);
					}
				}
				else
				{
					label1.Text = "指定的路径不存在！";
				}
			}
		}

		private void button2_Click(object sender, EventArgs e)
		{
			BackupFileToZip backupFileToZip = new BackupFileToZip(label1,checkBox1,textBox1,checkedListBox1,filePath);
			backupFileToZip.CreateGameSavedBackupFile();
		}

		private void checkBox1_CheckedChanged(object sender, EventArgs e)
		{
			if (checkBox1.Checked)
			{
				textBox1.Visible = true;
			}
			else 
			{
				textBox1 .Visible = false;
			}
		}

		private async void pictureBox1_Click(object sender, EventArgs e)
		{
			label1.Text = "正在刷新中……";
			checkedListBox1.Items.Clear();
			await Task.Delay(2000);
			ProgramInitialization();
		}

		private void pictureBox1_MouseEnter(object sender, EventArgs e)
		{
			ChangeBackColor.SetPanelNewColor(panel1);
		}

		private void pictureBox1_MouseLeave(object sender, EventArgs e)
		{
			ChangeBackColor.SetPanelOldColor(panel1);
		}

		private void button3_Click(object sender, EventArgs e)
		{
			new UnzipFile(backupZipPath, decompressionPath);
		}
	}
}
